package com.jzwl.system.base.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.google.gson.Gson;
import com.jzwl.system.admin.role.service.SysroleService;
import com.jzwl.common.cache.RedisService;
import com.jzwl.common.constant.GlobalConstant;

/**
 * controller基类，所有controller必须继承此类，此类也是封装各个controller层基本方法的地方
 * 
 * @author zhang guo yu
 * @version 1.0.0
 * @since 2015-02-01
 * */
@Component("baseController")
public class BaseController {

	@Autowired
	private RedisService redisService;
	@Autowired
	private SysroleService sysroleService;

	protected Map<String, Object> paramsMap = new HashMap<String, Object>();// http中请求参数所在的map

	/**
	 * 便于在前后台之间数据传递时，绑定并注入各种比如时间，DOUBLE类型的VO
	 * 
	 * @param binder
	 *            绑定池
	 * */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				new SimpleDateFormat("yyyy-MM-dd"), true));
		binder.registerCustomEditor(java.sql.Timestamp.class,
				new CustomDateEditor(
						new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
	}

	/**
	 * 对http请求中数据进行封装到Map中
	 * 
	 * @param request
	 * @return
	 */
	protected Map<String, Object> createParameterMap(HttpServletRequest request) {
		paramsMap.clear();
		Enumeration<String> paramKeys = request.getParameterNames();
		while (paramKeys.hasMoreElements()) {
			String key = paramKeys.nextElement();
			paramsMap.put(key, request.getParameter(key));
		}

		return paramsMap;
	}

	/**
	 * 返回参数key
	 * 
	 * @param req
	 */
	protected String getParamKey(HttpServletRequest request, String methodName) {
		try {
			String redis_key = methodName;

			Enumeration<String> enm = request.getParameterNames();

			while (enm.hasMoreElements()) {

				String name = enm.nextElement();

				if (name.indexOf("tj_") < 0) {
					String value = request.getParameter(name);
					value = URLEncoder.encode(value, "utf-8");
					redis_key += "|" + name + "-" + value;
				}

			}

			return redis_key;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	protected void putCache(String redis_key, int cacheTime, String result_json)
			throws UnsupportedEncodingException {
		if (null != result_json && !"null".equals(result_json)) {
			result_json = URLEncoder.encode(result_json, "utf-8");
			redisService.set(redis_key, result_json, cacheTime);//
		}
	}

	protected String getCache(String redis_key) {
		try {
			if (null != redis_key && !"null".equals(redis_key)) {

				String res = redisService.get(redis_key);//

				if (null != res) {

					res = URLDecoder.decode(res, "utf-8");

					return res;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 直接返回json
	 * 
	 * @param json
	 */
	protected void outWriteJSON(String json, HttpServletResponse response) {
		PrintWriter out = null;
		response.setCharacterEncoding(GlobalConstant.CHARACTER_ENCODING_PROJECT);
		response.setContentType(GlobalConstant.CONTENTTYPE_PROJECT_HTML);// IOS必须用json，xml不行
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.write(json);
		out.close();
	}

	protected void outWriteList(List<Map<String, Object>> list,
			String redis_key, int cacheTime, HttpServletResponse response)
			throws UnsupportedEncodingException {
		PrintWriter out = null;
		response.setCharacterEncoding(GlobalConstant.CHARACTER_ENCODING_PROJECT);
		response.setContentType(GlobalConstant.CONTENTTYPE_PROJECT_HTML);// IOS必须用json，xml不行
		Gson gson = new Gson();
		String result = gson.toJson(list).toString();
		putCache(redis_key, cacheTime, result);
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.write(result);
		out.close();
	}

	/**
	 * 返回参数拼接的key值
	 * 
	 * @param map
	 * @param methodName
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	protected String getParamKeyNew(Map<String, Object> map, String methodName) {
		try {
			String redis_key = methodName;

			Iterator<Entry<String, Object>> it = map.entrySet().iterator();

			while (it.hasNext()) {

				Map.Entry entry = (Map.Entry) it.next();
				String key = entry.getKey().toString();
				if (key.indexOf("tj_") < 0) {
					String value = "";
					if (null != entry.getValue()) {
						value = entry.getValue().toString();
						value = URLEncoder.encode(value, "utf-8");
					}
					redis_key += "|" + key + "-" + value;
				}
			}

			return redis_key;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取当前登录用户名
	 * 
	 * @return
	 */
	public String getCurrentUserName() {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String username = null;
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}
		return username;
	}

	/**
	 * 获取当前登录用户所拥有的权限
	 * 
	 * @return
	 */
	public List<String> getUserAuthorityList() {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		List list = new ArrayList<String>();
		if (principal instanceof UserDetails) {
			for (GrantedAuthority ga : ((UserDetails) principal)
					.getAuthorities()) {
				list.add(ga.getAuthority());
			}
		}
		return list;
	}

	/**
	 * 校验微信商家版权限，只允许店长店员登录 应该根据用户ID查询权限，匹配店长和店员的权限，然后返回true
	 * 
	 * @param userId
	 * @return
	 */
	protected boolean checkWxAuth(String userId) {
		boolean flag = false;
		try {
			Map<String, Object> pMap = new HashMap<String, Object>();
			pMap.put("userId", userId);
			List<Map<String, Object>> roleAllList = sysroleService
					.getRoleListByUserId(pMap);
			List<String> roleList = new ArrayList<String>();
			for (Map<String, Object> map : roleAllList) {
				if ("店长".equals((String) map.get("name"))) {
					flag = true;
					break;
				}
			}
			return flag;
		} catch (Exception e) {
			e.printStackTrace();
			return flag;
		}
	}

	/**
	 * 
	 * @param key
	 * @return
	 */
	public String getRedisParamValue(String key) {
		String value = null;
		try {

			value = redisService.get(key);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}
}
